package com.gmrz.uap.common;

import com.gmrz.uap.cfg.SystemConst;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HostFilterInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) {
        HttpServletRequest request = inv.getController().getRequest();
        HttpServletResponse response = inv.getController().getResponse();

        String serverName = request.getServerName();
        int serverPort = request.getServerPort();

        StringBuilder url = new StringBuilder();
        url.append(serverName).append(":").append(serverPort);

        boolean hostFilterEnable = PropKit.use(SystemConst.SYSTEM_CONFIG_FILE).getBoolean("host.filter.enable");

        if (hostFilterEnable) {
            boolean isVisit = false;

            String hostFilterUrl = PropKit.use(SystemConst.SYSTEM_CONFIG_FILE).get("host.filter.url");

            if (!StrKit.isBlank(hostFilterUrl)) {
                String[] hostFilterUrlArr = hostFilterUrl.split(SystemConst._DEFAULT_SEPARATOR_COMMA);

                for (int i = 0; i < hostFilterUrlArr.length; i++) {
                    if (url.toString().equals(hostFilterUrlArr[i])) {
                        isVisit = true;
                        break;
                    }
                }
            }

            if (!isVisit) {
                inv.getController().renderError(403);
            }
        }

        inv.invoke();

    }
}
